package com.tanhua.dubbo.api.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.mongodb.client.result.UpdateResult;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.Visitors;
import com.tanhua.dubbo.vo.PageInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

@DubboService(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplateSave;

    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        //判断该访客今日是否已经访问过
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").lte(maxDate), //同一个字段添加多个条件时需要使用andOperator()
                        Criteria.where("date").gte(minDate))
        );

        Visitors visitors = this.mongoTemplate.findOne(query, Visitors.class);
        if (null != visitors) {
            //TODO 更新用户信息（选择性）--完成
            //查询上次访问我的时间
            Query updateQuery = Query.query(Criteria.where("id").is(visitors.getId()));
            //更新时间
            Update update = Update.update("data", System.currentTimeMillis());
            UpdateResult updateResult = this.mongoTemplate.updateFirst(updateQuery, update, Visitors.class);
            return visitors.getId().toString();
        }

        //记录访客信息
        visitors = new Visitors();
        visitors.setId(ObjectId.get());
        visitors.setUserId(userId);
        visitors.setVisitorUserId(visitorUserId);
        visitors.setDate(System.currentTimeMillis());
        visitors.setFrom(from);
        this.mongoTemplate.save(visitors);

        return visitors.getId().toString();
    }

    @Override
    public List<Visitors> queryMyVisitor(Long userId) {
        PageRequest pageRequest = PageRequest.of(0, 5, Sort.by(Sort.Order.desc("date")));
        Criteria criteria = Criteria.where("userId").is(userId);
        //查询该用户上一次查询列表的时间
        //TODO 查询列表的时间，在项目实战中查询列表中写入 --完成
        String hashKey = Convert.toStr(userId);
        Object lastDate = this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, hashKey);
        if (null != lastDate) {
            criteria.and("date").gte(Convert.toLong(lastDate));
        }

        this.redisTemplate.opsForHash().put(VISITOR_REDIS_KEY,hashKey,Convert.toStr(System.currentTimeMillis()));

        Query query = Query.query(criteria).with(pageRequest);
        return  this.mongoTemplate.find(query, Visitors.class);
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }

//com.tanhua.dubbo.server.api.VisitorsApiImpl


    private List<Visitors> queryList(Query query, Long userId){
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        //查询每个来访用户的得分
        for (Visitors visitors : visitorsList) {

            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId())
            );
            RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class);
            if(ObjectUtil.isNotEmpty(recommendUser)){
                visitors.setScore(recommendUser.getScore());
            }else {
                //默认得分
                visitors.setScore(90d);
            }
        }

        return visitorsList;
    }

    /**
     * 按照时间倒序排序，查询最近的访客信息
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Visitors> topVisitor(Long userId, Integer page, Integer pageSize) {

        PageInfo<Visitors> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);

        //记录查询时间到Redis
        String hashKey = Convert.toStr(userId);
        String value = Convert.toStr(System.currentTimeMillis());
        this.redisTemplate.opsForHash().put(VISITOR_REDIS_KEY, hashKey, value);

        //PageInfo<Visitors> pageInfo = new PageInfo<>(page, pageSize);
        pageInfo.setRecords(visitorsList);
        return pageInfo;
    }
}
